<?php


namespace App\Services\Tools;
// 支付宝 支 第三方  付  继曲科技
use App\Exceptions\BasicException;
use App\Models\MainDB\UserRecharge;
use App\Repositories\LogRepository;
use App\Services\Business\BusinessConfigService;
use Illuminate\Support\Facades\Log;

class QuJinPay
{
    // 回调查询一下
    // 域名网关 支付请求地址
    private $urls;
    // 支付接口
    private $payURL;
    // 检查接口
    private $queryURL;
    // 标题
    private $merchantSubject;
    private $refundURL;
//    // 私钥
//    private $PrivateKey;
//    // 公钥
//    private $PublicKey;

    public function __construct()
    {
        $this->urls = 'https://pay.guangzhi3.com';
        $this->payURL = '/checkout/trade/pay.html';
        $this->queryURL = '/checkout/trade/query.html';
        $this->refundURL = '/checkout/refund/do.html';
        $this->merchantSubject = '心伴';
    }

    /**
     * @param $orderSn
     * @param $money
     * @param $pay_type
     * @param $business_id
     * @param $param
     * @param $userIp
     * @param $user_id
     * @return string
     * @throws \App\Exceptions\BasicException
     */
    public function AliPay($orderSn, $money, $business_id, $param, $userIp, $user_id, $pay_type = "ALIPAY")
    {
        $timestamps = date('Y-m-d H:i:s', strtotime("+2 hour"));
        $amount = abs(floatval($money)) * 100;
        $data = [
            "sappId" => $param['sappId'],          // sappid
//            "sappId" => "9fyg3dv426zn7o22",          // sappid
            "subMchid" => $param['subMchid'],   // 二级商户id,不同的支付类型，值不一样
//            "subMchid" => $param['merchantID'],   // 二级商户id,不同的支付类型，值不一样
            "outOrderId" => $orderSn,           // 设置商户订单号
            "subject" => "充值".$amount."到".$user_id,      // 订单主题
//            "subject" =>  $this->merchantSubject."_".$user_id,      // 订单主题
            "amount" => abs(floatval($money)) * 100,          // 订单金额，单位：分
//            "amount" => $money,          // 订单金额，单位：分
            "payType" => $pay_type,      // 设置支付类型，支付宝订单
            "orderType" => 0,    //订单类型
            "prodType" => "APP", //支付产品类型，App支付
            "userIp" => $userIp,             //客户端IP,用户发起支付的IP 获取规则请参考
            "notifyUrl" => $param['notifyUrl'], //回调地址通知URL
            "expireTime" => $timestamps, //风控通知URL
//            "disablePayChannels" => "pcredit,creditCard",
            "extInfo" => json_encode([
                'business_id' => $business_id
            ])
        ];
        // 获取时间
//        $sign_data = base64_encode(json_encode($data));
////        Log::info("data: ".$sign_data);
//        $key = "-----BEGIN PRIVATE KEY-----\n" . $param['merchantPrivateKey'] . "\n-----END PRIVATE KEY-----";
//        if (!openssl_sign($sign_data, $signature, $key, OPENSSL_ALGO_SHA256)) {
//            throw new BasicException(-1, '加签失败!');
//        }
//        $sign = base64_encode($signature);
////        Log::info("sign: ".$sign);

        $aesTool = new QJAesService($param['merchantPrivateKey'], $data);
        $sign = $aesTool->signature();

        $data_new = [
            "appSecKey" => $param['appSecKey'],
            "signType" => "RSA2",
            "timeStamp" => date('Y-m-d H:i:s'),
            "version" => "1.0",
            "bizStr" => base64_encode(json_encode($data)),
//            "bizStr" => "eyJzYXBwSWQiOiI5ZnlnM2R2NDI2em43bzIyIiwic3ViTWNoaWQiOiIyMDg4MDYwODk5MzgxOTc4Iiwib3V0T3JkZXJJZCI6IjIwMjQxMDE4MjQ3MDk1ODg1NjMyIiwic3ViamVjdCI6Ilx1NTM0M1x1OGJlZFx1N2E3YVx1OTVmNCIsImFtb3VudCI6MTAwLCJwYXlUeXBlIjoiQUxJUEFZIiwib3JkZXJUeXBlIjowLCJwcm9kVHlwZSI6IkFQUCIsInVzZXJJcCI6IjExOC4yNTAuMTA4LjIzIiwibm90aWZ5VXJsIjoiaHR0cDpcL1wvMTIxLjQxLjUxLjEyMDo5MDAxXC9hcGlcL3RoaXJkUGF5XC9hbGlQYXlOb3RpZnkiLCJleHBpcmVUaW1lIjoiMjAyNC0xMC0xOCAxNDoxMTo0OSIsImV4dEluZm8iOiJ7XCJidXNpbmVzc19pZFwiOjYxfSJ9",
            "sign" => $sign
//            "sign" => "HZyVb+I9Ueq9MeHLQD8Y4eqBBFe/91ITrVaEANMhy5EZ7tyMn/kxNqgtEyW0Nmx9DU7NGtopp2xQ2dD26svnQHkBKx1GrlnUGYX6hKdHJf3G1W4ehA8QD2C5tLn8K7xxVCICYhZZI1FjPF5ly4fc3x/jvYhL9jB6xjmMfdRDuybkZ0IZJAAEot5AQAaKUVSzFxYNsCkM+pvM3iE82GilTkFESFWn4Pfl9UnC1A3MR7tMsSOD5t7jnM1NCSJMMKat9kz8sxHq5GT5V0CJnKDKHEEPwXGRx4M52ZI6b/noi04jp86T8osQwXbcZRSni+DsR/ATmdVG6yhHi1D+SsULCQ==",
        ];
//        Log::info("param: ".json_encode($data_new));
        $result = $this->get_curl_request($this->urls . $this->payURL, $data_new);
//        $logRtx = new LogRepository("qujin-pay");
//        $logRtx->log("return::", $result);
//        $logRtx->File();
        if ($result['code'] != '200') {
            $logRtx = new LogRepository("qujin-pay");
            $logRtx->log("err::", $result);
            $logRtx->File();
            return '';
        }
        $result_info = json_decode(base64_decode($result['bizStr'], true), true);
        if (!$result_info['success']) {
            $logRtx = new LogRepository("qujin-pay");
            $logRtx->log("result_info_err::", $result_info);
            $logRtx->File();
            return '';
        }
//        $logRtx = new LogRepository("qujin-pay");
//        $logRtx->log("result_info_err::", $result_info['data']['orderStr']);
//        $logRtx->File();
        return $result_info['data']['orderStr'];
    }

    /**
     * @param $order_id
     * @return mixed
     * @throws BasicException
     */
    public function Refund($order_id)
    {
        $businessConfigService = new BusinessConfigService();
        $info = UserRecharge::query()->where('order_sn',$order_id)->first();
//        return $info;
        $config = $businessConfigService->getById($info['business_config_id']);
        if ($config === null || empty($config->params)) {
            throw new BasicException(-1, '未获取到商户配置!');
        }
        $businessConfig = $config->params;
        $data = [
            "orderId" => "2c9b818e967692830196a6aa2e10393c",
            "refundId" => date("Ymd").time(),
            "reason" => "退款".$info['money']."到{$info['user_id']}",
            "refundAmount" => intval(abs(floatval($info['money'])) * 100),  // 分
        ];
        Log::info("请求参数". json_encode($data));
        $sign_data = base64_encode(json_encode($data));
        $key = "-----BEGIN PRIVATE KEY-----\n" . $businessConfig['merchantPrivateKey'] . "\n-----END PRIVATE KEY-----";
        if (!openssl_sign($sign_data, $signature, $key, OPENSSL_ALGO_SHA256)) {
            throw new BasicException(-1, '加签失败!');
        }
        $sign = base64_encode($signature);
        $data_new = [
            "appSecKey" => $businessConfig['appSecKey'],
            "signType" => "RSA2",
            "timeStamp" => date('Y-m-d H:i:s'),
            "version" => "1.0",
            "bizStr" => base64_encode(json_encode($data)),
            "sign" => $sign
        ];
        $result = $this->get_curl_request($this->urls . $this->refundURL, $data_new);
        $logRtx = new LogRepository("qujin-pay");
        $logRtx->log("return::", $result);
        $logRtx->File();
        if ($result['code'] != '200') {
            $logRtx = new LogRepository("qujin-pay");
            $logRtx->log("err::", $result);
            $logRtx->File();

        }
        return $result;
    }
    /**
     * @param $url
     * @param $data_new
     * @return mixed
     */
    public static function get_curl_request($url, $data_new)
    {
        Log::info("请求地址：".$url);
        Log::info("请求传参：".json_encode($data_new));
//        $logRtx = new LogRepository("qujin-pay");
//        $logRtx->log("url::", $url);
//        $logRtx->File();
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data_new));
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json;charset=utf-8', 'Accept: application/json'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
//        Log::info("fanhui: " . json_encode($output));
        $logRtx = new LogRepository("qujin-pay");
        $logRtx->log("request::", $output);
        $logRtx->File();
        return json_decode($output, true);

    }

}
